#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
// #include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>

#define DEVICE_CNT 1           // 设备号个数
#define NEW_LED_NAME "new_led" // 设备名称

#define BUS_IOC (0xFD5F8000)
#define BUS_IOC_GPIO1A_IOMUX_SEL_L (BUS_IOC + 0x0020) // gpio1 (A0-A3)的寄存器地址
#define VCCIO1_4_IOC (0xFD5F9000)
#define VCCIO1_4_IOC_GPIO1A_DS_L (VCCIO1_4_IOC + 0x0020)

#define GPIO1_BASE (0xFEC20000)
#define GPIO_SWPORT_DR_L (GPIO1_BASE + 0x0000)  // GPIO数据寄存器   0 -> Low(低电平) 1 ->High(高电平)
#define GPIO_SWPORT_DDR_L (GPIO1_BASE + 0x0008) // GPIO方向寄存器  0 -> Input  1 -> Output

/* 映射后的寄存器虚拟地址指针 */
static void __iomem *BUS_IOC_GPIO1A_IOMUX_SEL_L_PI;
static void __iomem *VCCIO1_4_IOC_GPIO1A_DS_L_PI;
static void __iomem *GPIO_SWPORT_DR_L_PI;
static void __iomem *GPIO_SWPORT_DDR_L_PI;

/*设备结构体*/
struct nwechrled_dev
{
    dev_t devid;           // 设备号
    struct cdev cdev;      // 字符设备结构体
    struct class *class;   // 类
    struct device *device; // 设备
    int major;             // 主设备号
    int minor;             // 次设备号
};

static struct nwechrled_dev newchrled;

/**
 * @brief 映射LED寄存器
 */
void led_remap(void)
{
    BUS_IOC_GPIO1A_IOMUX_SEL_L_PI = ioremap(BUS_IOC_GPIO1A_IOMUX_SEL_L, 4);
    VCCIO1_4_IOC_GPIO1A_DS_L_PI = ioremap(VCCIO1_4_IOC_GPIO1A_DS_L, 4);
    GPIO_SWPORT_DR_L_PI = ioremap(GPIO_SWPORT_DR_L, 4);
    GPIO_SWPORT_DDR_L_PI = ioremap(GPIO_SWPORT_DDR_L, 4);
}

/**
 * @brief 取消映射LED寄存器
 */
void led_unmap(void)
{
    iounmap(BUS_IOC_GPIO1A_IOMUX_SEL_L_PI);
    iounmap(VCCIO1_4_IOC_GPIO1A_DS_L_PI);
    iounmap(GPIO_SWPORT_DR_L_PI);
    iounmap(GPIO_SWPORT_DDR_L_PI);
}

/*
led 开关灯函数
*/
void led_switch(u8 cmd)
{
    u32 regVal;
    if (cmd > 0)
    {
        regVal = readl(GPIO_SWPORT_DR_L_PI);
        regVal |= (1 << 3) | (1 << (16 + 3));
        writel(regVal, GPIO_SWPORT_DR_L_PI);
    }
    else
    {
        regVal = readl(GPIO_SWPORT_DR_L_PI);
        regVal &= ~(1 << 3);
        regVal |= (1 << (16 + 3));
        writel(regVal, GPIO_SWPORT_DR_L_PI);
    }
}

static int led_open(struct inode *inode, struct file *filp)
{
    filp->private_data = &newchrled; // 设置私有数据
    printk("led open ok!\r\n");
    return 0;
}

static ssize_t led_read(struct file *filp, char __user *buf, size_t count, loff_t *pos)
{
    return 0;
}

static ssize_t led_write(struct file *filp, const char __user *buf, size_t count, loff_t *pos)
{
    int retvalue;
    unsigned char databuf[1];
    unsigned char ledstat;

    retvalue = copy_from_user(databuf, buf, count);
    if (retvalue < 0)
    {
        printk(KERN_INFO "kernel write failed!\r\n");
        return -EFAULT;
    }

    ledstat = databuf[0]; /* 获取状态值 */

    if (ledstat > 0)
    {
        led_switch(1); /* 打开 LED 灯 */
    }
    else
    {
        led_switch(0); /* 关闭 LED 灯 */
    }

    // 返回实际写入的字节数
    return count;
}

static int led_release(struct inode *inode, struct file *filp)
{
    printk("led release ok!\r\n");
    return 0;
}

/* 设备操作函数 */
static struct file_operations led_fops = {
    .owner = THIS_MODULE,
    .open = led_open,
    .read = led_read,
    .write = led_write,
    .release = led_release,
};

/*
 * @description : 驱动出口函数
 * @param : 无
 * @return : 无
 */
static int __init led_init(void)
{
    int retvalue = 0;
    u32 val = 0;
    /* 初始化 LED */
    /* 1、寄存器地址映射 */
    led_remap();
    /* 2、设置 GPIO1_A3 为 GPIO 功能。*/
    val = readl(BUS_IOC_GPIO1A_IOMUX_SEL_L_PI);
    val &= ~(0XF000 << 0);                /* bit15:12，清零 */
    val |= ((0XF000 << 16) | (0X0 << 0)); /* bit31:28 置 1，允许写 bit15:12，bit15:12：0，用作 GPIO1_A3 */
    writel(val, BUS_IOC_GPIO1A_IOMUX_SEL_L_PI);
    /* 3、设置 GPIO0_C0 驱动能力为 40ohm */
    val = readl(VCCIO1_4_IOC_GPIO1A_DS_L_PI);
    val &= ~(0X7000 << 0);                   /* bit14:12 清零*/
    val |= ((0X7000 << 16) | (0X6000 << 0)); /* bit30:28 置 1，允许写 bit14:12，192 bit14:12：110， 用作 GPIO1_A3 */
    writel(val, VCCIO1_4_IOC_GPIO1A_DS_L_PI);
    /* 4、设置 GPIO1_A3 为输出 */
    val = readl(GPIO_SWPORT_DDR_L_PI);
    val &= ~(0X8 << 0);                /* bit3 清零*/
    val |= ((0X8 << 16) | (0X8 << 0)); /* bit19 置 1，允许写 bit3，bit3，高电平 */
    writel(val, GPIO_SWPORT_DDR_L_PI);

    /* 5、设置 GPIO1_A3 为低电平，关闭 LED 灯。*/
    val = readl(GPIO_SWPORT_DR_L_PI);
    val &= ~(0X8 << 0); /* bit3 清零*/
    val |= (0X8 << 16); /* bit19 置 1，允许写 bit3，
    bit3，低电平 */
    writel(val, GPIO_SWPORT_DR_L_PI);

    /* 注册字符设备驱动 */
    /*1. 创建设备号*/
    if (newchrled.major) /* 指定主设备号*/
    {
        /*这行代码的作用是创建一个设备号（dev_t类型）并赋值给 newchrled.devid。*/
        newchrled.devid = MKDEV(newchrled.major, 0);

        retvalue = register_chrdev_region(newchrled.devid, DEVICE_CNT, NEW_LED_NAME);

        if (retvalue < 0)
        {
            pr_err("无法注册 %s 字符驱动 [retvalue = %d]\n", NEW_LED_NAME, DEVICE_CNT);
            goto fail_map;
        }
    }
    else /* 动态分配设备号*/
    {
        retvalue = alloc_chrdev_region(&newchrled.devid, 0, DEVICE_CNT, NEW_LED_NAME);
        if (retvalue < 0)
        {
            pr_err("%s 字符驱动无法申请设备号 [retvalue = %d]\n", NEW_LED_NAME, DEVICE_CNT);
            goto fail_map;
        }
        newchrled.major = MAJOR(newchrled.devid); // 获取主设备号
        newchrled.minor = MINOR(newchrled.devid); // 获取次设备号
    }
    printk("%s 模块初始化成功 [major = %d,minor = %d]\n", NEW_LED_NAME, newchrled.major, newchrled.minor);

    //2. 初始化 cdev
    newchrled.cdev.owner = THIS_MODULE;
    cdev_init(&newchrled.cdev, &led_fops);
    /*3. 添加 cdev */
    retvalue = cdev_add(&newchrled.cdev, newchrled.devid, DEVICE_CNT);
    if (retvalue < 0)
    {
        printk("cdev_add fail\n");
        goto del_unregister;
    }
    //4. 创建类
    newchrled.class = class_create(THIS_MODULE, NEW_LED_NAME);
    if (IS_ERR(newchrled.class))
    {
        goto del_cdev;
    }

    //5. 创建设备
    newchrled.device = device_create(newchrled.class, NULL, newchrled.devid, NULL, NEW_LED_NAME);
    if (IS_ERR(newchrled.device))
    {
        goto destroy_class;
    }
    printk("led init ok!\n");
    return 0;

destroy_class:
    class_destroy(newchrled.class);
del_cdev:
    cdev_del(&newchrled.cdev);
del_unregister:
    unregister_chrdev_region(newchrled.devid, DEVICE_CNT);
fail_map:
    led_unmap();
    return -EIO;
}

void __exit led_exit(void)
{
    led_unmap();

    cdev_del(&newchrled.cdev);
    unregister_chrdev(DEVICE_CNT, NEW_LED_NAME);
    device_destroy(newchrled.class, newchrled.devid);
    class_destroy(newchrled.class);
    printk("led exit ok!\r\n");
}

module_init(led_init);
module_exit(led_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("JACK");
MODULE_INFO(intree, "Y");
